// script.js
document.addEventListener('DOMContentLoaded', function() {
    // 导出全部数据
    document.getElementById('exportAllBtn').addEventListener('click', exportAllData);
    
    // 导出当前企业数据
    document.getElementById('exportCurrentBtn').addEventListener('click', exportCurrentCompanyData);
    // 当前选中的公司ID
    let currentCompanyId = null;
    
    // 导出全部数据
    function exportAllData() {
        const data = [];
        
        supplyChainData.relationships.forEach(relation => {
            const fromCompany = supplyChainData.companies.find(c => c.id === relation.from);
            const toCompany = supplyChainData.companies.find(c => c.id === relation.to);
            
            relation.goods.forEach(good => {
                data.push({
                    '供货方': fromCompany.name,
                    '收货方': toCompany.name,
                    '货物名称': good.name,
                    '规格型号': good.spec,
                    '单位': good.unit,
                    '数量': good.quantity,
                    '单价(元)': good.price
                });
            });
        });
        
        exportToExcel(data, '供应链全部数据');
    }
    
    // 导出当前企业数据
    function exportCurrentCompanyData() {
        if (!currentCompanyId) return;
        
        const data = [];
        const company = supplyChainData.companies.find(c => c.id === currentCompanyId);
        
        // 上游数据
        const upstreamRelations = supplyChainData.relationships.filter(r => r.to === currentCompanyId);
        upstreamRelations.forEach(relation => {
            const fromCompany = supplyChainData.companies.find(c => c.id === relation.from);
            
            relation.goods.forEach(good => {
                data.push({
                    '供货方': fromCompany.name,
                    '收货方': company.name,
                    '货物名称': good.name,
                    '规格型号': good.spec,
                    '单位': good.unit,
                    '数量': good.quantity,
                    '单价(元)': good.price
                });
            });
        });
        
        // 下游数据
        const downstreamRelations = supplyChainData.relationships.filter(r => r.from === currentCompanyId);
        downstreamRelations.forEach(relation => {
            const toCompany = supplyChainData.companies.find(c => c.id === relation.to);
            
            relation.goods.forEach(good => {
                data.push({
                    '供货方': company.name,
                    '收货方': toCompany.name,
                    '货物名称': good.name,
                    '规格型号': good.spec,
                    '单位': good.unit,
                    '数量': good.quantity,
                    '单价(元)': good.price
                });
            });
        });
        
        exportToExcel(data, `${company.name}供应链数据`);
    }
    
    // 导出到Excel
    function exportToExcel(data, fileName) {
        const csvContent = "data:text/csv;charset=utf-8," 
            + "供货方,收货方,货物名称,规格型号,单位,数量,单价(元)\n" 
            + data.map(item => Object.values(item).join(',')).join('\n');
        
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", `${fileName}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    // 供应链数据
    const supplyChainData = {
        companies: [
            { id: 1, name: "奇瑞汽车股份有限公司", level: "核心企业" },
            // { id: 2, name: "芜湖普威技研有限公司", level: "一级供应商" },
            { id: 2, name: "芜湖普威技研有限公司", level: "一级供应商" },
            // { id: 3, name: "安庆明豪汽车科技有限公司", level: "二级供应商" },
            { id: 3, name: "安庆明豪汽车科技有限公司", level: "二级供应商" },
            { id: 4, name: "芜湖科诚机械制造有限公司", level: "三级供应商" },
            { id: 5, name: "芜湖虹飞机械有限公司", level: "四级供应商" },
            { id: 6, name: "河南新楚金属材料有限公司", level: "五级供应商" },
            { id: 7, name: "河南北楚实业有限公司", level: "六级供应商" },
            { id: 8, name: "河南宝日通机械加工有限公司", level: "七级供应商" },
            { id: 9, name: "芜湖中楚汽车零部件有限公司", level: "八级供应商" },
            { id: 10, name: "芜湖同创模具机械有限公司", level: "九级供应商" },
            { id: 11, name: "泊头市丰裕精密铸造有限公司", level: "十级供应商" },
            { id: 12, name: "河北青峰车体模具有限公司", level: "十一级供应商" }
        ],
        relationships: [
            { from: 2, to: 1, goods: [
                    { name: "交交通运输设备*仪表板横梁本体总成", spec: "401001118AA", unit: "件", quantity: 2610, price: 154.24 },
                    { name: "交通运输设备*仪表板横梁本体总成", spec: "401001632AA", unit: "件", quantity: 1498, price: 125.96 },
                    { name: "交通运输设备*仪表板横梁总成", spec: "401000688AA", unit: "件", quantity: 7103, price: 115.16 },
                    { name: "交通运输设备*仪表板横梁总成", spec: "401001284AB", unit: "件", quantity: 362, price: 131 },
                    { name: "交通运输设备*仪表板横梁总成", spec: "401001529AA", unit: "件", quantity: 745, price: 120.4 },
                    { name: "交通运输设备*仪表板横梁总成", spec: "401001530AA", unit: "件", quantity: 812, price: 159.72 },
                    { name: "交通运输设备*制动踏板总成", spec: "204002138AC", unit: "件", quantity: 7911, price: 57.16 },
                    { name: "交通运输设备*后围总成", spec: "501001632AA", unit: "件", quantity: 4917, price: 79.58 },
                    { name: "交通运输设备*左前翼子板前安装支架总成", spec: "501001719AA", unit: "件", quantity: 10943, price: 5.16 },
                    { name: "交通运输设备*右前翼子板前安装支架总成", spec: "501001720AA", unit: "件", quantity: 11088, price: 5.16 }
                ]},
            { from: 4, to: 3, goods: [
                    { name: "锻件*PEPS模块安装支架总成", spec: "T15-5301055A", unit: "件", quantity: 10332, price: 0.83 },
                    { name: "锻件*前围板安装支架焊接分总成", spec: "T15-5301010-4", unit: "件", quantity: 10332, price: 5.31 },
                    { name: "锻件*转向管柱安装支架焊接分总成", spec: "J73-5301010-3", unit: "件", quantity: 10332, price: 6.99 },
                    { name: "锻件*吊装支架-左", spec: "AAA100001", unit: "件", quantity: 5882, price: 0.94 },
                    { name: "锻件*IP主定位支架", spec: "AAA100004", unit: "件", quantity: 5882, price: 0.85 },
                    { name: "锻件*IP副定位支架", spec: "AAA100005", unit: "件", quantity: 5882, price: 1.1 },
                    { name: "锻件*线束支架", spec: "AAA100006", unit: "件", quantity: 5882, price: 0.32 },
                    { name: "锻件*PAB支架-左", spec: "AAA100007", unit: "件", quantity: 11644, price: 0.44 }
                ]},
            { from: 3, to: 2, goods: [
                    { name: "交通运输设备*仪表板横梁总成", spec: "401000688AA", unit: "件", quantity: 3130, price: 99.86 },
                    { name: "交通运输设备*T18FL3仪表板横梁总成", spec: "401001974AA", unit: "件", quantity: 7659, price: 107.78 }
                ]},
            { from: 5, to: 4, goods: [
                    { name: "锻件*上板焊接费", spec: "SC2E-2810020-HJ-01", unit: "件", quantity: 48532, price: 3.42 },
                    { name: "黑色金属冶炼压延品*钢材", spec: "T1D-110/111后背门左/右气弹簧加强板总成", unit: "件", quantity: 180045, price: 4.13 }
                ]},
            { from: 6, to: 5, goods: [
                    { name: "黑色金属冶炼压延品*冷轧卷", spec: "0.8*1000*C", unit: "吨", quantity: 22, price: 4424 },
                    { name: "黑色金属冶炼压延品*酸洗板", spec: "6.0*1210*1080", unit: "吨", quantity: 2.47, price: 4234 },
                    { name: "黑色金属冶炼压延品*酸洗卷", spec: "2.5*1440", unit: "吨", quantity: 7.9, price: 4017 }
                ]},
            { from: 7, to: 6, goods: [
                    { name: "黑色金属冶炼压延品*冷轧卷", spec: "1.5mm", unit: "吨", quantity: 8.66, price: 5425 },
                    { name: "黑色金属冶炼压延品*冷轧卷", spec: "1.2mm", unit: "吨", quantity: 9.27, price: 5014 },
                    { name: "黑色金属冶炼压延品*冷轧卷", spec: "1.0mm", unit: "吨", quantity: 7.7, price: 5353 }
                ]},
            { from: 8, to: 7, goods: [
                    { name: "交通运输设备*前保安装支架总成", spec: "501009340AA", unit: "件", quantity: 2000, price: 1.1 },
                    { name: "交通运输设备*DCDC安装支架总成", spec: "501009454AA", unit: "件", quantity: 2000, price: 3.65 },
                    { name: "交通运输设备*前保横梁本体", spec: "C11-2803711", unit: "件", quantity: 2200, price: 10.52 },
                    { name: "交通运输设备*前端结构安装板总成", spec: "C11-2803760", unit: "件", quantity: 4000, price: 2.67 },
                    { name: "交通运输设备*前挡板横梁分总成", spec: "C11-5300250", unit: "件", quantity: 1920, price: 7.6 },
                    { name: "交通运输设备*仪表横梁左安装支架总成", spec: "C11-5300350", unit: "件", quantity: 1800, price: 3.28 },
                ]},
            { from: 9, to: 8, goods: [
                    { name: "三通比例阀安装支架", spec: "302002153AA", unit: "件", quantity: 28726, price: 0.255 },
                    { name: "制动踏板支架", spec: "501007221AA", unit: "件", quantity: 28336, price: 1.012 },
                    { name: "A柱下内饰护板左安装支架", spec: "403008693AA", unit: "件", quantity: 26613, price: 0.255 },
                    { name: "CCB安装加强板", spec: "501008498AA", unit: "件", quantity: 20932, price: 0.817 },
                    { name: "空调外安装支架", spec: "501008731AA", unit: "件", quantity: 45304, price: 0.358 }
                ]},
            { from: 10, to: 9, goods: [
                    { name: "模具*流水槽本体", spec: "501008378AA PI+CPI", unit: " ", quantity: 0.3, price: 270796 },
                    { name: "模具*流水槽加强版", spec: "501009190AA PI+CPI", unit: " ", quantity: 0.3, price: 204070 },
                    { name: "模具*流水槽加强版", spec: "501009190AA TR+CTR", unit: " ", quantity: 0.3, price: 197433 }
                ]},
            { from: 11, to: 10, goods: [
                    { name: "金属铸件", spec: "HT300", unit: "吨", quantity: 78, price: 6283 },
                    { name: "金属铸件", spec: "GM246", unit: "吨", quantity: 17, price: 9557 },
                    { name: "金属铸件", spec: "GM241", unit: "吨", quantity: 13, price: 8230 },
                    { name: "金属铸件", spec: "ICD-5", unit: "吨", quantity: 3, price: 11327 }
                ]},
            { from: 12, to: 11, goods: [
                    { name: "金属铸件", spec: "HT300", unit: "吨", quantity: 84, price: 5132 }
                ]}
        ]
    };

    // 渲染供应链图谱
    const supplyChainElement = document.getElementById('supplyChain');
    const detailsPanel = document.getElementById('detailsPanel');
    const companyNameElement = document.getElementById('companyName');
    const detailsContentElement = document.getElementById('detailsContent');
    const closeBtn = document.getElementById('closeBtn');

    // 创建公司节点
    function createCompanyNodes() {
        // 按层级排序
        const sortedCompanies = [...supplyChainData.companies].sort((a, b) => {
            if (a.level === '核心企业') return -1;
            if (b.level === '核心企业') return 1;
            return parseInt(a.level) - parseInt(b.level);
        });

        sortedCompanies.forEach(company => {
            const node = document.createElement('div');
            node.className = `company-node ${company.level === '核心企业' ? 'core' : `level-${parseInt(company.level)}`}`;
            node.dataset.id = company.id;
            
            node.innerHTML = `
                <div class="company-name">${company.name}</div>
                <div class="company-level">${company.level}</div>
            `;
            
            node.addEventListener('click', () => showCompanyDetails(company.id));
            supplyChainElement.appendChild(node);
        });
    }

    // 显示公司详情
    function showCompanyDetails(companyId) {
        currentCompanyId = companyId;
        const company = supplyChainData.companies.find(c => c.id === companyId);
        companyNameElement.textContent = company.name;
        
        // 收集所有货物名称用于比较
        const allGoodsNames = new Set();
        
        // 查找上游关系
        const upstreamRelations = supplyChainData.relationships.filter(r => r.to === companyId);
        const upstreamGoods = [];
        if (upstreamRelations.length > 0) {
            upstreamRelations.forEach(relation => {
                relation.goods.forEach(g => allGoodsNames.add(g.name));
                upstreamGoods.push(...relation.goods);
            });
        }
        
        // 查找下游关系
        const downstreamRelations = supplyChainData.relationships.filter(r => r.from === companyId);
        const downstreamGoods = [];
        if (downstreamRelations.length > 0) {
            downstreamRelations.forEach(relation => {
                relation.goods.forEach(g => allGoodsNames.add(g.name));
                downstreamGoods.push(...relation.goods);
            });
        }
        
        let allHtml = '';
        let upstreamHtml = '';
        let downstreamHtml = '';
        
        // 生成上游HTML
        if (upstreamRelations.length > 0) {
            upstreamRelations.forEach(relation => {
                const supplier = supplyChainData.companies.find(c => c.id === relation.from);
                const goodsHtml = `
                    <div class="relationship">
                        <div class="relationship-title">购买 ${supplier.name} 的货物</div>
                        ${createGoodsTable(relation.goods, downstreamGoods)}
                    </div>
                `;
                allHtml += goodsHtml;
                upstreamHtml += goodsHtml;
            });
        } else {
            const noDataHtml = `<div class="relationship">
                <div class="relationship-title">上游供应商</div>
                <p class="no-data">无上游供应商信息</p>
            </div>`;
            allHtml += noDataHtml;
            upstreamHtml += noDataHtml;
        }
        
        // 生成下游HTML
        if (downstreamRelations.length > 0) {
            downstreamRelations.forEach(relation => {
                const customer = supplyChainData.companies.find(c => c.id === relation.to);
                const goodsHtml = `
                    <div class="relationship">
                        <div class="relationship-title">供应给 ${customer.name} 的货物</div>
                        ${createGoodsTable(relation.goods, upstreamGoods)}
                    </div>
                `;
                allHtml += goodsHtml;
                downstreamHtml += goodsHtml;
            });
        } else {
            const noDataHtml = `<div class="relationship">
                <div class="relationship-title">下游客户</div>
                <p class="no-data">无下游客户信息</p>
            </div>`;
            allHtml += noDataHtml;
            downstreamHtml += noDataHtml;
        }
        
        document.getElementById('allTab').innerHTML = allHtml || '<p>点击左侧企业节点查看详细信息</p>';
        document.getElementById('upstreamTab').innerHTML = upstreamHtml;
        document.getElementById('downstreamTab').innerHTML = downstreamHtml;
        
        // 添加tab切换事件
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                btn.classList.add('active');
                document.getElementById(`${btn.dataset.tab}Tab`).classList.add('active');
            });
        });
        detailsPanel.style.display = 'flex';
    }

    // 创建货物表格
    function createGoodsTable(goods, compareGoods) {
        if (!goods || goods.length === 0) {
            return '<p class="no-data">无货物信息</p>';
        }
        
        // 获取比较货物中的所有名称
        const compareNames = new Set();
        if (compareGoods && compareGoods.length > 0) {
            compareGoods.forEach(item => compareNames.add(item.name));
        }
        
        let table = `
            <table class="goods-table">
                <thead>
                    <tr>
                        <th>货物名称</th>
                        <th>规格型号</th>
                        <th>单位</th>
                        <th>数量</th>
                        <th>单价(元)</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        goods.forEach(item => {
            const isHighlight = compareNames.has(item.name);
            table += `
                <tr>
                    <td class="${isHighlight ? 'highlight' : ''}">${item.name}</td>
                    <td>${item.spec}</td>
                    <td>${item.unit}</td>
                    <td>${item.quantity}</td>
                    <td>${item.price}</td>
                </tr>
            `;
        });
        
        table += `
                </tbody>
            </table>
        `;
        
        return table;
    }

    // 关闭详情面板
    closeBtn.addEventListener('click', () => {
        detailsPanel.style.display = 'none';
    });

    // 初始化
    createCompanyNodes();
});